import { ref } from 'vue'
import { supabase } from '../../lib/supabase'
import type { CommentForm, CommentAction } from './types'

export const useCommentOperations = () => {
  // 操作状态
  const isSubmitting = ref(false)
  const isLiking = ref(false)
  const isReplying = ref(false)
  const submitError = ref<string | null>(null)
  const likeError = ref<string | null>(null)
  const replyError = ref<string | null>(null)

  // 提交评论
  const submitComment = async (movieId: number, form: CommentForm): Promise<boolean> => {
    try {
      isSubmitting.value = true
      submitError.value = null

      // 获取当前用户
      const { data: { user }, error: userError } = await supabase.auth.getUser()
      if (userError || !user) {
        throw new Error('用户未登录')
      }

      // 提交评论
      const { data, error } = await supabase
        .from('comments')
        .insert({
          movie_id: movieId,
          user_id: user.id,
          content: form.content,
          parent_id: form.parentId || null
        })
        .select()
        .single()

      if (error) {
        throw new Error(`提交评论失败: ${error.message}`)
      }

      return true
    } catch (err) {
      submitError.value = err instanceof Error ? err.message : '提交评论失败'
      console.error('提交评论失败:', err)
      return false
    } finally {
      isSubmitting.value = false
    }
  }

  // 点赞评论
  const likeComment = async (commentId: number): Promise<{ success: boolean; action?: string; error?: string }> => {
    try {
      isLiking.value = true
      likeError.value = null

      // 获取当前用户
      const { data: { user }, error: userError } = await supabase.auth.getUser()
      if (userError || !user) {
        throw new Error('用户未登录')
      }

      // 使用数据库函数处理点赞
      const { data, error } = await supabase
        .rpc('handle_comment_vote', {
          p_user_id: user.id,
          p_comment_id: commentId,
          p_vote_type: 1
        })

      if (error) {
        throw new Error(`点赞失败: ${error.message}`)
      }

      if (!data || !data.success) {
        throw new Error(data?.error || '点赞失败')
      }

      return { success: true, action: data.action }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '点赞失败'
      likeError.value = errorMessage
      console.error('点赞评论失败:', err)
      return { success: false, error: errorMessage }
    } finally {
      isLiking.value = false
    }
  }

  // 点踩评论
  const dislikeComment = async (commentId: number): Promise<{ success: boolean; action?: string; error?: string }> => {
    try {
      isLiking.value = true
      likeError.value = null

      // 获取当前用户
      const { data: { user }, error: userError } = await supabase.auth.getUser()
      if (userError || !user) {
        throw new Error('用户未登录')
      }

      // 使用数据库函数处理点踩
      const { data, error } = await supabase
        .rpc('handle_comment_vote', {
          p_user_id: user.id,
          p_comment_id: commentId,
          p_vote_type: -1
        })

      if (error) {
        throw new Error(`点踩失败: ${error.message}`)
      }

      if (!data || !data.success) {
        throw new Error(data?.error || '点踩失败')
      }

      return { success: true, action: data.action }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '点踩失败'
      likeError.value = errorMessage
      console.error('点踩评论失败:', err)
      return { success: false, error: errorMessage }
    } finally {
      isLiking.value = false
    }
  }

  // 删除评论
  const deleteComment = async (commentId: number): Promise<boolean> => {
    try {
      // 获取当前用户
      const { data: { user }, error: userError } = await supabase.auth.getUser()
      if (userError || !user) {
        throw new Error('用户未登录')
      }

      // 检查评论是否存在且属于当前用户
      const { data: comment, error: checkError } = await supabase
        .from('comments')
        .select('user_id')
        .eq('id', commentId)
        .single()

      if (checkError) {
        throw new Error(`评论不存在: ${checkError.message}`)
      }

      if (comment.user_id !== user.id) {
        throw new Error('只能删除自己的评论')
      }

      // 删除评论
      const { error: deleteError } = await supabase
        .from('comments')
        .delete()
        .eq('id', commentId)

      if (deleteError) {
        throw new Error(`删除评论失败: ${deleteError.message}`)
      }

      return true
    } catch (err) {
      console.error('删除评论失败:', err)
      return false
    }
  }

  // 获取评论统计
  const getCommentStats = async (movieId: number) => {
    try {
      const { data, error } = await supabase
        .rpc('get_comment_stats', { p_movie_id: movieId })

      if (error) {
        console.error('获取评论统计失败:', error)
        return null
      }

      return data
    } catch (err) {
      console.error('获取评论统计失败:', err)
      return null
    }
  }

  return {
    // 状态
    isSubmitting,
    isLiking,
    isReplying,
    submitError,
    likeError,
    replyError,
    
    // 方法
    submitComment,
    likeComment,
    dislikeComment,
    deleteComment,
    getCommentStats
  }
}
